/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-30 09:56:03
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-08-15 21:51:07
 * @description:
 */

import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
  ScrollView,
  View,
  Text,
  SafeAreaView,
  Image,
  Platform
} from 'react-native'
import { ListItem } from 'react-native-elements'
import ImagePicker from 'react-native-image-picker'
import DateTimePicker from '@react-native-community/datetimepicker'
import { Picker, DatePicker } from 'native-base'
import ListRightElement from '@/components/ListRightElement'
import TextPop from '@/components/TextPop'
import styles from './styles'
import * as userActions from '@/actions/user'

const defaultHeader = require('@/assets/images/default-header.png')

const EditInfo = props => {
  const now = new Date()
  const today =
    now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate()
  const userInfo = useSelector(state => state.user.userInfo)
  const dispatch = useDispatch()
  const [headerImg, setHeaderImg] = useState(userInfo.headImg)
  const [birthday, setBirthday] = useState(userInfo.birthday || today)
  const [datePickerShow, setDatePickerShow] = useState(false)
  const [sex, setSex] = useState(userInfo.gender)
  const [nickName, setNickName] = useState(userInfo.nickName)
  const [nickNamePop, setNickNamePop] = useState(false)
  const [sign, setSign] = useState(userInfo.introduce)
  const [signPop, setSignPop] = useState(false)

  const updateInfo = params => {
    dispatch(userActions.updateUserInfo(params))
  }

  // 选择头像
  const imagePickerOptions = {
    title: '选择一张图片作为您的头像',
    takePhotoButtonTitle: '拍照',
    chooseFromLibraryButtonTitle: '从相册选择',
    cancelButtonTitle: '取消',
    maxWidth: 200,
    maxHeight: 200,
    quality: 0.5,
    noData: true,
    storageOptions: {
      skipBackup: true,
      path: 'images'
    }
  }

  const _onChangeHeader = () => {
    ImagePicker.showImagePicker(imagePickerOptions, response => {
      console.log('Response = ', response)

      if (response.didCancel) {
        console.log('User cancelled image picker')
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error)
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton)
      } else {
        // const source = 'data:image/jpeg;base64,' + response.data
        let file
        if (Platform.OS === 'android') {
          file = response.uri
        } else {
          file = response.uri.replace('file://', '')
        }

        dispatch(
          userActions.uploadFile(file, response.type, response.fileName)
        ).then(res => {
          setHeaderImg(res)
          updateInfo({ headImg: res })
        })
      }
    })
  }

  const _onChangeSex = value => {
    console.log('changeSex:', value)
    setSex(value)
    updateInfo({ sex: value })
  }

  const _onChangeBirthday = date => {
    let dateObj = new Date(date)
    let dateStr =
      dateObj.getFullYear() +
      '-' +
      (dateObj.getMonth() + 1) +
      '-' +
      dateObj.getDate()
    setBirthday(dateStr)
    // setDatePickerShow(false)
    updateInfo({ birthday: dateStr })
  }

  const _onSubmitChangeNickName = value => {
    setNickNamePop(false)
    setNickName(value)
    updateInfo({ nickName: value })
  }

  const _onSubmitChangeSign = value => {
    setSignPop(false)
    setSign(value)
    updateInfo({ introduce: value })
  }

  const _onCancelChangeNickName = () => {
    setNickNamePop(false)
  }

  const _onCancelChangeSign = () => {
    setSignPop(false)
  }

  console.log('birthday:', birthday)
  return (
    <>
      {/* <StatusBar barStyle="dark-content" backgroundColor="#fff"/> */}
      {/* <Headers title="编辑资料" /> */}
      <SafeAreaView style={styles.wrap}>
        <ScrollView
          style={styles.container}
          contentInsetAdjustmentBehavior="automatic"
        >
          <TextPop
            visible={nickNamePop}
            defaultValue={nickName}
            onSubmit={_onSubmitChangeNickName}
            onCancel={_onCancelChangeNickName}
          />
          <TextPop
            visible={signPop}
            defaultValue={sign}
            onSubmit={_onSubmitChangeSign}
            onCancel={_onCancelChangeSign}
          />
          <View style={styles.listWrap}>
            <ListItem
              onPress={() => _onChangeHeader()}
              contentContainerStyle={styles.list}
              title="头像"
              bottomDivider
              rightIcon={
                <ListRightElement>
                  {headerImg ? (
                    <Image
                      source={{
                        uri: headerImg
                      }}
                      style={styles.header}
                    />
                  ) : (
                    <Image source={defaultHeader} style={styles.header} />
                  )}
                </ListRightElement>
              }
            />
            <ListItem
              onPress={() => {
                setNickNamePop(true)
              }}
              contentContainerStyle={styles.list}
              title="昵称"
              bottomDivider
              rightIcon={
                <ListRightElement>
                  <Text style={styles.listText}>{nickName}</Text>
                </ListRightElement>
              }
            />
            <ListItem
              onPress={() => {
                setSignPop(true)
              }}
              contentContainerStyle={styles.list}
              title="介绍"
              bottomDivider
              rightIcon={
                <ListRightElement>
                  <Text style={styles.listText} numberOfLines={1}>
                    {sign}
                  </Text>
                </ListRightElement>
              }
            />
            <ListItem
              contentContainerStyle={styles.list}
              title="性别"
              bottomDivider
              rightIcon={
                <ListRightElement>
                  <Picker
                    placeholder="选择性别"
                    selectedValue={sex}
                    style={styles.sexPickerStyle}
                    itemStyle={styles.sexPickerItem}
                    textStyle={{ color: '#999' }}
                    onValueChange={item => _onChangeSex(item)}
                    headerBackButtonText="取消"
                    iosHeader="选择性别"
                  >
                    <Picker.Item label="男" value={0} />
                    <Picker.Item label="女" value={1} />
                  </Picker>
                </ListRightElement>
              }
            />
            <ListItem
              onPress={() => {
                setDatePickerShow(true)
              }}
              contentContainerStyle={styles.list}
              title="生日"
              bottomDivider
              rightIcon={
                <ListRightElement>
                  <DatePicker
                    defaultDate={new Date(birthday)}
                    minimumDate={new Date(1920, 1, 1)}
                    maximumDate={new Date()}
                    locale="zh-cn"
                    timeZoneOffsetInMinutes={undefined}
                    modalTransparent={true}
                    animationType={'slide'}
                    androidMode={'default'}
                    placeHolderText={birthday}
                    textStyle={{ color: '#999' }}
                    placeHolderTextStyle={{ color: '#999' }}
                    onDateChange={date => {
                      _onChangeBirthday(date)
                    }}
                    disabled={false}
                  />
                </ListRightElement>
              }
            />
            {datePickerShow && (
              <DateTimePicker
                testID="dateTimePicker"
                value={new Date(birthday)}
                mode="date"
                is24Hour={true}
                display="default"
                locale="zh_cn"
                maximumDate={new Date()}
                minimumDate={new Date(1920, 1, 1)}
                onChange={_onChangeBirthday}
              />
            )}
          </View>
        </ScrollView>
      </SafeAreaView>
    </>
  )
}

export default EditInfo
